package me.leiusual.sharing.ui.store

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import com.bumptech.glide.load.resource.bitmap.FitCenter
import dagger.android.support.DaggerFragment
import kotlinx.android.synthetic.main.fragment_store_home.*
import me.leiusual.sharing.R
import me.leiusual.sharing.repository.model.Data
import me.leiusual.sharing.ui.MainViewModel
import me.leiusual.sharing.ui.helper.HandleObserver
import me.leiusual.sharing.ui.store.adapter.StoreHomeAdapter
import me.leiusual.sharing.ui.store.dialog.StoreCategoryDialog
import me.leiusual.sharing.util.extension.setImageUrl
import timber.log.Timber
import javax.inject.Inject

/**
 * Create by leiusual on 2018/7/15
 */
class StoreHomeFragment : DaggerFragment(), View.OnClickListener {

  @Inject
  lateinit var factory: ViewModelProvider.Factory

  private val mainViewModel: MainViewModel by activityViewModels { factory }

  private val viewModel: StoreHomeViewModel by viewModels { factory }

  private val args: StoreHomeFragmentArgs by navArgs()

  // 标记Tab位置
  private var currentItem = 1

  // 默认或选中或指定的店铺ID
  private val storeId: Long
    get() = if (args.storeId > 0) args.storeId else viewModel.store.currentStoreId

  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_store_home, container, false)
  }

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    toolbar.setNavigationOnClickListener {
      findNavController().popBackStack()
    }

    text_view_category.setOnClickListener(this)

    // viewPager
    view_pager.adapter = StoreHomeAdapter(childFragmentManager)

    observeData()
    viewModel.storeDetail(storeId)
  }

  override fun onDestroyView() {
    super.onDestroyView()

    // 记录下当前位置
    currentItem = view_pager.currentItem
  }

  override fun onClick(v: View?) {
    when (v?.id) {
      R.id.text_view_category -> {
        StoreCategoryDialog.newInstance(storeId).showNow(childFragmentManager, StoreCategoryDialog::class.simpleName)
      }
    }
  }

  private fun observeData() {
    mainViewModel.category.observe(viewLifecycleOwner, Observer {
      Timber.v("category = %s", it)

      // 更新menu
      text_view_category.text = it.level0.name + "> "
      if (it.level1 != null) {
        text_view_category.append(it.level1.name + "> ")
      }
      if (it.level2 != null) {
        text_view_category.append(it.level2.name + "> ")
      }

      // 更新商区
      val adapter = view_pager.adapter as StoreHomeAdapter
      adapter.submitCategory(it.level2?.id ?: it.level1?.id ?: it.level0.id)
    })

    viewModel.storeDetail.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("storeDetail = %s", it)
      when (it) {
        is Data.Loading -> {
          state_constraint_layout.showProgress()
        }
        is Data.Error -> {
          state_constraint_layout.showError(it.error.message)
        }
        is Data.Success -> {
          state_constraint_layout.showContent()

          // 更新LOGO，店铺名称
          image_view_logo.setImageUrl(it.data.logoUrl) { glideRequest -> glideRequest.transform(FitCenter()) }
          text_view_title.text = it.data.storeName

          // 更新商区
          val adapter = view_pager.adapter as StoreHomeAdapter
          adapter.submitMap(storeId, it.data.description, it.data.storeAreaIdNameMap)

          // 获取上一次的位置
          view_pager.setCurrentItem(currentItem, false)
        }
      }
    })
  }
}